
#include "clock.h"

//can add 256 counters totally
//use CLK_ADDCLK(int counter) to all clock, these clocks will plus 1 with every 1ms time interval
#define MAX_CLK 4

//1ms interrupt (24MHz)
#define TH_24M_1MS 0xf8
#define TL_24M_1MS 0x2f

static volatile uchar clkid=0;
static volatile uint *pclk[MAX_CLK];
static volatile uint delay=0;

void CLK_INIT()
{
	TMOD(CLKTIMERID,1);
	TH(CLKTIMERID)=TH_24M_1MS;
	TL(CLKTIMERID)=TL_24M_1MS;
	ET(CLKTIMERID)=1;

	CLK_ADDCLK(&delay);
}

bool CLK_ADDCLK(uint *ctAdd)
{
	if(clkid >= MAX_CLK) return false;

	TR(CLKTIMERID)=0;
	ET(CLKTIMERID)=0;

	pclk[clkid]=ctAdd;
	clkid++;

	ET(CLKTIMERID)=1;
	TR(CLKTIMERID)=1;

	return true;
}

void CLK_DELAY(uint ct) {
	delay=0;
	for(;delay<ct;) {;}
}

void clock_timer(void) interrupt CLKTIMERINTID
{
	uchar i;
	TL(CLKTIMERID)+=TL_24M_1MS+2;
	TH(CLKTIMERID)+=TH_24M_1MS;

	for(i=0;i<clkid;i++)
		(*pclk[i])++;

}
